/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package DAO;

import DAO.util.ConectaBanco;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import model.Chave;
import model.Time;

/**
 *
 * @author Alberto
 */
public class ChaveDAO {
     public boolean criar(Chave chave) {
        try {

            Connection conexao = ConectaBanco.getConexao();

            String sql = "insert into chaves(id, id_time)values (?,?)";

            PreparedStatement pstmt = conexao.prepareStatement(sql);

            pstmt.setInt(1, chave.getId_chave());
            pstmt.setInt(2, chave.getTime().getId_time());
            

            pstmt.execute();
            conexao.close();

            return true;

        } catch (SQLException sql) {
            sql.printStackTrace();
            return false;

        }

    }

    public ArrayList<Chave> buscarTodas(int id) {
        ArrayList<Chave> chaves = new ArrayList<Chave>();
        Connection conexao = null;
        try {
            conexao = ConectaBanco.getConexao();
            String sql = "select * from chaves where id=?";

            PreparedStatement pst = conexao.prepareStatement(sql);

            ChaveDAO chaveDAO = new ChaveDAO();
            TimeDAO timeDAO = new TimeDAO();
            pst.setInt(1, id);
            ResultSet rs = pst.executeQuery();
            while (rs.next()) {
                Chave chave = new Chave();
                chave.setId_chave(rs.getInt("id"));
                chave.setTime(timeDAO.buscarPorId(rs.getInt("idTime")));
                chaves.add(chave);
            }
                conexao.close();
            return chaves;

        } catch (Exception sql) {
            System.out.println("Erro ao buscar um aluno" + sql.getMessage());
            return null;
        }

    }
}
